package com.xuzz.study.springbootdemo.controller;

import com.xuzz.study.springbootdemo.service.WebSocketServer;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
@RequestMapping("/upload")
public class UploadController extends BaseController {

    /**
     * 使用ServletFileUpload
     * 需要配置spring.servlet.multipart.enabled=false
     * @param request
     * @return
     */
    @RequestMapping
    @CrossOrigin
    public ResponseEntity upload(HttpServletRequest request)
    {
        HashMap params = this.getUploadFiles(request);
        System.out.println(params);


        Executors.newSingleThreadExecutor().submit(new Runnable() {
            @Override
            public void run() {
                try {
                    String wsId = "1";
                    if (params.containsKey("wsId")) {
                        wsId = String.valueOf(params.get("wsId"));
                    }

                    for (int i = 1; i <= 100; i++) {
                        WebSocketServer.sendInfo(i + "", wsId);
                        Thread.sleep(1000l);
                    }
                }
                catch (Exception e)
                {

                }
            }
        });
        return ResponseEntity.of(Optional.of("uploaded"));
    }

    /**
     * 需要配置：spring.servlet.multipart.enabled=true
     * @param request
     * @param files
     * @return
     */
    @RequestMapping("/upload2")
    @CrossOrigin
    public ResponseEntity upload2(HttpServletRequest request, @RequestParam(value="file")MultipartFile[] files)
    {
        int i = null==files?0:files.length;
        return ResponseEntity.of(Optional.of(i));
    }

    @RequestMapping("/upload3")
    public ResponseEntity addLeak(HttpServletRequest request)  throws Exception
    {
        HashMap params = null;
        if(ServletFileUpload.isMultipartContent(request))
        {
            params = this.getUploadFiles(request);
        }
        else
        {
            params=this.getParamMap(request);
        }

        return ResponseEntity.ok("haa");
    }
}
